# coding=utf-8

def GetHRefs():
    rs = []
    with open('urls.txt') as f:
        for r in f.readlines(): 
            r = r.strip()
            # name = r[r.rfind("/")+1:]
            r = r.replace(r"http://learnvimscriptthehardway.stevelosh.com/", "")
            rs.append(r)
            # print("curl -o %s %s" % (name, r))
    return rs

def GetNames():
    rs = []
    with open('contents.txt') as f:
        for r in f.readlines(): 
            r = r.strip()
            # name = r[r.rfind("/")+1:]
            rs.append(r)
            # print("curl -o %s %s" % (name, r))
    return rs
# coding=utf-8

# import re
from collections import namedtuple
from mobi_lib import BuildOPF, BuildNCX, BuildTOC

# PATTERN1 = """<li>\n<p><a href="([^"]+)">([^<]+)</a></p>\n(<ul>\n((<li><a href="([^"]+)">([^<]+)</a></li>\n)+)</ul>\n)?</li>"""
# PATTERN2 = """<li><a href="([^"]+)">([^<]+)</a></li>\n"""
# with open("LearnVimscriptTheHardWay.html", encoding="utf-8") as f:
#     s = f.read()

t = namedtuple('FileItem', 'text href id sf')
st = namedtuple('SubFileItem', 'text anchor id')

# def Data(filename):
def Data():
    hrefs = GetHRefs()
    names = GetNames()
    print( len(hrefs) , len(names) )
    assert len(hrefs) == len(names)
    rs = []
    for (h, n, i) in zip(hrefs, names, range(len(hrefs))):
        rs.append(t(n, h, str(i), []))
    return rs

    with open(filename, encoding="utf-8") as f:
        s = f.read()
    id = 0
    it1 = re.finditer(PATTERN1, s)
    rs = []
    for p1 in it1:
        print(p1.group(1), p1.group(2))
        ss = []
        if p1.group(3):
            it2 = re.finditer(PATTERN2, p1.group(3))
            for p2 in it2:
                print("*" * 5, p2.group(1), p2.group(2))
                # id += 1
                ss.append(st(p2.group(2), p2.group(1), str(id)))
        id += 1
        rs.append(t(str(id) + " " + p1.group(2), p1.group(1), str(id), ss))
    return rs

if __name__ == "__main__":
    # data = Data("LearnVimscriptTheHardWay.html")
    data = Data()
    print(data)
    # exit()
    # return
    # print(BuildTOC(data))
    # with open("index.html", "w") as f:
    #     f.write(BuildTOC(data))
    print(BuildOPF(data, "LearnVimscriptTheHardWay.ncx", "preface.html", "index.html"))
    with open("LearnVimscriptTheHardWay.opf", "w") as f:
        f.write(BuildOPF(data, "LearnVimscriptTheHardWay.ncx", "preface.html", "index.html"))
    print(BuildNCX(data))
    with open("LearnVimscriptTheHardWay.ncx", "w") as f:
        f.write(BuildNCX(data))
